package com.ccp.dev.system.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.base.BaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.model.SubSystem;
import com.ccp.dev.system.model.SysRole;
import com.ccp.dev.system.model.SysUserColumnRes;
import com.ccp.dev.system.service.ResourcesService;
import com.ccp.dev.system.service.SysUserColumnResService;
import com.ccp.dev.system.util.SubSystemUtil;
import com.ccp.dev.system.util.SysRoleUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 首页用户栏目内容 信息操作处理控制器
 * 
 * @author huangyan
 * @date 2019-07-25 08:59:55
 */
@Controller
@Action(ownermodel = SysAuditModelType.HOME_MANAGEMENT)
@RequestMapping("/system/sysUserColumnRes")
public class SysUserColumnResController extends BaseController
{
	@Resource
	private SysUserColumnResService sysUserColumnResService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: huangyan
     * @date: 2019-07-25 08:59:55
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到首页用户栏目内容首页",exectype = "页面跳转日志")
    public String list() {
        return "sysUserColumnRes/list";
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: huangyan
     * @date: 2019-07-25 08:59:55
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到首页用户栏目内容新增页面",exectype = "页面跳转日志")
    public String add(HttpServletRequest request,ModelMap modelMap) {
        String userColResId = RequestUtil.getString(request,"userColResId");
        modelMap.put("userColResId",userColResId);
        return getAutoView();
    }

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: sysUserColumnRes 保存的对象
     * @return: java.lang.Object
     * @auther: huangyan
     * @date: 2019-07-25 08:59:55
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存首页用户栏目内容数据",
            detail = "<#if add>添加<#else>更新</#if>首页用户栏目内容数据<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    public Object save(@RequestBody SysUserColumnRes sysUserColumnRes,HttpServletRequest request) {
        String id = sysUserColumnRes.getUserColResId();
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("add", true);
            //新增操作
            //新增数据前生成随机UserColResId  和创建时间
            sysUserColumnRes.setUserColResId(UUIDUtils.getUUIDFor32());
            int i = sysUserColumnResService.add(sysUserColumnRes);
            if (i > 0) {
                SysAuditThreadLocalHolder.putParamerter("success", true);
                return success("数据保存成功!");
            } else {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("数据保存失败!");
            }
        } else {
            SysAuditThreadLocalHolder.putParamerter("add", false);
            //修改操作
            int rs = sysUserColumnResService.update(sysUserColumnRes);
            if (rs > 0) {
                SysAuditThreadLocalHolder.putParamerter("success", true);
                return success("数据更新成功!");
            } else {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("数据更新失败!");
            }
        }

    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"userColResId"
     * @return: java.lang.Object
     * @auther: huangyan
     * @date: 2019-07-25 08:59:55
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除首页用户栏目内容数据",
            detail = "根据主键ID删除首页用户栏目内容数据<#if success>成功<#else>失败</#if>",
            exectype = "删除日志")
    public Object delete(@RequestParam("userColResId") String[] id) {
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("删除失败，未传入数据唯一标识!");
        }
        int i = sysUserColumnResService.delByIdArray(id);;
        if (i > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return success("删除成功!");
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("删除失败!");
        }
    }
    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"userColResId"
     * @return: java.lang.Object
     * @auther: huangyan
     * @date: 2019-07-25 08:59:55
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询首页用户栏目内容的一条数据",
            exectype = "查询日志")
    public Object get(@RequestParam("id") String userColResId) {
        SysUserColumnRes sysUserColumnRes = sysUserColumnResService.getOneById(userColResId);

        if (null == sysUserColumnRes) {
            return fail("未获取对应数据!");
        }
        return success(sysUserColumnRes, "获取数据成功!");
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: huangyan
     * @date: 2019-07-25 08:59:55
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询首页用户栏目内容",exectype = "查询日志")
    public Object list(HttpServletRequest request) {

        QueryFilter queryFilter = new QueryFilter(request, true);
        //分页数据
        List<SysUserColumnRes> pageDatas = sysUserColumnResService.queryList(queryFilter);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 首页用户应用信息
     * @author huangyan
     * @date 2019/7/25
     * @param request
    */
    @RequestMapping("/userRes")
    @ResponseBody
    @Action(description="获取用户应用信息",
            detail = "获取用户应用信息<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    public ResultData userRes(HttpServletRequest request) {
        try {

            //栏目id
            String columnAlias = request.getParameter("columnAlias");

            //用户id
            String userId = ContextUtil.getCurrentUserId();

            //角色id
            SysRole sysRole = SysRoleUtil.getCurrentRole(request);
            String roleId = null != sysRole ? sysRole.getRoleId() : null;

            //子系统id
            SubSystem currentSystem = SubSystemUtil.getCurrentSystem(request);
            String systemId = null != currentSystem ? currentSystem.getSystemId() : null;

            List<Map<String, Object>> userResList = sysUserColumnResService.getUserRes(userId, columnAlias);
            List<Map<String, Object>> nonUserResList = sysUserColumnResService.getNonUserRes(systemId, roleId, userId, columnAlias);

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("userResList", userResList);
            resultMap.put("nonUserResList", nonUserResList);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return success(resultMap,"获取用户应用信息成功");

        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail(e.getMessage());
        }

    }

    /**
     * 首页保存用户应用信息
     * @author huangyan
     * @date 2019/7/25
     * @param columnAlias 栏目别名
     * @param resIds   资源id数组
    */
    @RequestMapping("/saveUserRes")
    @ResponseBody
    @Action(description="保存当前用户主页栏目应用信息",
            detail = "保存当前用户主页栏目应用信息<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    public ResultData saveUserRes(String columnAlias, String[] resIds) {

        try {
            //用户id
            String userId = ContextUtil.getCurrentUserId();

            //要保存的应用
            if (resIds == null) {
                resIds = new String[0];
            }
            List<String> newList = Arrays.asList(resIds);

            //保存前我的应用
            List<Map<String, Object>> userResList = sysUserColumnResService.getUserRes(userId, columnAlias);
            if (userResList == null) {
                userResList = new ArrayList<>();
            }
            List<String> existList = new ArrayList<>();
            for (Map<String, Object> map : userResList) {
                if (map != null) {
                    String resId = (String) map.get("resId");
                    existList.add(resId);
                }
            }

            //要新增的
            List<String> addList = newList.stream().filter(t -> !existList.contains(t)).collect(Collectors.toList());
            //要删除的
            List<String> delList = existList.stream().filter(t -> !newList.contains(t)).collect(Collectors.toList());

            sysUserColumnResService.saveUserColRes(userId, columnAlias, addList, delList);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return success("保存用户应用信息成功");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail(e.getMessage());
        }
    }


}
